
import Vue from 'vue';
import Message from './elementui-message.js';
import router from '../../router';
import store from '../../store'
import { Loading } from 'element-ui';

let util = {
  logout(){
    Vue.$cookies.remove('Authorization');
    localStorage.removeItem('Authorization');
    location.href = "#/";
  },
  isBlank(value){
    //undefined == null
    return value == null || value == '' || value == 'null';
  },
  goback(){
    if(history.state){
      router.back(-1);
    }else{
      router.push('/');
    }
  },
  checkTextForbid(value){
    if(value.length > 512){
      Message('超出最大字符长度');
      return true;
    }
    if(value.length < 5){
      Message('最少5个字符');
      return true;
    }
    return false;
  },
  searchKeyExcute(store, input, route){
    if(route.path.indexOf('/index/allBook') < 0){
      router.push('/index/allBook?keyword='+input);
    }else{
      store.commit('searchKeyExcute', input);
    }
  },
  getUserInfo(vm){
    vm.$http.postFormInit('/user/userInfo', null, res=>{
      vm.userInfo = res;
      vm.$cookies.set("nickname", res.nickName, 0);
    });
  },
  pieceURLParam(param){
    // console.log(param);
    let arr = Object.keys(param);
    let url = "";
    for(let i=0,j=0,length=arr.length; i<length; i++){
      let key = arr[i];
      if(param[key] != null && param[key] != undefined && param[key] !== ""){
        if(j == 0){
          url += "?";
        }else{
          url += "&";
        }
        url += key + "=" + param[key];
        j++;
      }
    }
    // console.log(url);
    return url;
  },
  getHtmlText(htmlStr){
    if(htmlStr){
      return htmlStr.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ').replace(/&.*?;/g,"");
    }else{
      return "";
    }
  },
  valueOfString(str){
    if(str == undefined || str == null){
      return null;
    }
    return str.toString();
  },
  openLoading(){
    store.state.loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
  },
  closeLoading(){
    if(store.state.loading){
      store.state.loading.close();
    }
  },
  goAnother(global, url){
    // console.log("go:"+url);
    if(global.goBookDetailType == "_blank"){
      window.open(router.resolve(url).href, '_blank');
    }else{
      router.push(url);
    }
  },
  openUrl(url){
    window.open(url, '_blank');
  }
}

export default util